package com.example.java_gobang.utils;

import com.example.java_gobang.contant.Contants;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;

import java.security.Key;
import java.util.Date;
import java.util.Map;

/**
 *
 */
public class JwtUtils {
    private static final long JWT_EXPIRATION = 60*60*1000;
    //密匙
    private static final String secretKey = "vYsvJXG6WUn5GVVpiB1JDj2VsjfebuOlR28S/WuTltE=";
    //⽣成安全密钥
    private static Key key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretKey));

    /**
     * 生成Token
     * @param claim
     * @return
     */
    public static String getToken(Map<String,Object> claim){
        Date date = new Date(JWT_EXPIRATION+System.currentTimeMillis());
        //生成token
        String jwt = Jwts.
                builder().
                setClaims(claim).
                setExpiration(date).
                signWith(key).
                compact();
        return jwt;//token
    }

    /**
     * 校验Token
     * @param token
     * @return
     */
    public static Claims parseToken(String token){
        //创建解析器，设置密钥
        JwtParser builder = Jwts.parserBuilder().setSigningKey(key).build();
        Claims claims = null;
        try {
            //解析token
            claims = builder.parseClaimsJws(token).getBody();
        }catch (Exception e){

        }
        return claims;
    }
    /**
     * 根据token获取id
     */
    public static Integer getIdByToken(String token){
        //校验解析token
        Claims claims = parseToken(token);
        if(claims == null){
            //用户未登录
            return null;
        }
        //获取id
        Integer userId = (Integer) claims.get(Contants.TOKEN_USER_ID);
        System.out.println(userId);
        return userId;
    }
}
